package com.chengww.grab_rp.activities

import androidx.lifecycle.MutableLiveData
import com.chengww.grab_rp.api.LoginResponse
import com.chengww.grab_rp.api.NetworkManager
import com.chengww.grab_rp.api.PluginService
import com.chengww.grab_rp.api.RequestBody
import com.chengww.grab_rp.base.BaseViewModel
import com.chengww.grab_rp.database.user.User
import com.chengww.grab_rp.database.user.UserDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * Created by chengww on 2/20/21
 * @author chengww
 */
class LoginViewModel(private val userDao: UserDao): BaseViewModel() {

    private val service: PluginService by lazy { NetworkManager.pluginService }

    val pluginId = MutableLiveData<String>()

    val md5Key = MutableLiveData<String>()

    val loginResponse = MutableLiveData<LoginResponse>()

    fun login(plugId: String, md5Key: String) {
        launch(null, {
            val body = RequestBody().put("plugid", plugId).put("md5_key", md5Key).sign(md5Key)
            service.login(body)
        }) {
            // Login success
            withContext(Dispatchers.IO) {
                userDao.insert(User(md5Key, it.plugId ?: "", it.token ?: ""))
            }
            loginResponse.value = it
        }
    }
}